
var wait = 60;//发送短信重试间隔
	//发送短信方法
	function send(o,flag) {
		if(!flag){
			return;
		}		
        if (wait == 60) {//第一次秒数
            o.setAttribute("disabled", true);//按钮不可编辑
            var phone=$(".row .col-lg-7 #phone").val();//获取电话号码
            $.get("/sendMsg/"+phone,function (data) {//发送验证码
                if (data.success == true) {
                	showPopover($("#msgBtn"),"验证码发送成功");
                } else {
                	showPopover($("#msgBtn"),"验证码发送失败:"+data.errMsg);
                    o.removeAttribute("disabled");//启用发送短信验证码按钮
                    wait = 60;
                    flag=false;
                }                               
                return;
            });
        }
        if (wait == 0) {
            o.removeAttribute("disabled");
            $("#msgBtn").html("获取验证码");
            wait = 60;
        } else {
            o.setAttribute("disabled", true);
            if (wait <60) {
                $("#msgBtn").html("<span style='margin-left: -12px;'>"+wait + "s后可重新发送</span>");
            }
            wait--;
            startJob=setTimeout(function () {
                if (wait == 0) {
                    flag = true
                };
                send(o, flag)
            }, 1000)
        }
	}
	//提示框，2s自动消失
	function showPopover(target, msg) {
		  target.attr("data-original-title", msg);
		  $('[data-toggle="popover"]').tooltip();
		  target.tooltip('show');
		  target.focus();
		  //2秒后消失提示框
		  var id = setTimeout(function (){
		      target.attr("data-original-title", "");
		      target.tooltip('hide');
		    }, 2000);
	}
	
document.onkeydown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (e && e.keyCode === 13) {
        $("#btnSubmit1").click();
    }
};

$("#msgBtn").click(function(){
	send(this,true);
});

$('#register').on('hide.bs.modal', function () {
	$('#registerForm').bootstrapValidator('resetForm');//关闭模态框时重置表单
});

$('#picture').click(function(){
	this.src="getPicCode?timestamp="+ new Date().getTime();
});
/*坑：表单按钮type='submit' 或用<button>标签时会自动提交不需要什么onclick....除非用<input> type='button',(前者表单自动刷新)*/

$("#headPicture").fileinput({                
	language: 'zh', //设置语言
    uploadUrl: "/file", //上传的地址
    allowedFileExtensions: ['jpg','png','jpeg','png'],//接收的文件后缀
    //showUploadedThumbs:false,
    // uploadClass: 'hidden',
    showRemove:false,
    showClose:false,
    showCancel:false,
    showUpload: false, //是否显示上传按钮
    showCaption: false,//是否显示标题
    //browseClass: "btn btn-info", //按钮样式
    overwriteInitial:true,
    dropZoneEnabled: false,//是否显示拖拽区域
    //minImageWidth: 150, //图片的最小宽度
    //minImageHeight: 150,//图片的最小高度
    maxImageWidth: 500,//图片的最大宽度
    maxImageHeight: 500,//图片的最大高度
    maxFileSize: 50,//单位为kb，如果为0表示不限制文件大小
    enctype: 'multipart/form-data',
    validateInitialCount: false,
    previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
    fileActionSettings : {
        showUpload: false,
        //showRemove: false,
        showZoom:false
    }
})

var isOk=true;//全局变量
$("#resetPassword").click(function(){//忘记密码
	var username=$("#passForm #username").val();
	if(username==""){
		showPopover($("#passForm #username"),"请输入用户名");
		return;
	}
	bootbox.setDefaults("locale","zh_CN");
	bootbox.prompt({ 
		size: "small",
		title: "请输入绑定的邮箱：", 
		callback: function(email){
			$.ajaxSettings.async = false;//设为同步,不然一直转
			if(email!=null){
				//1.验证邮箱和用户名是否匹配
				$.get("/user/checkUser?username="+username+"&email="+email,function(result){
					//2如果匹配：发送邮件，并提示成功
					if(!result.success){
						toastr.error("输入邮箱与绑定邮箱不一致，请核实!", "提示");
						isOk=false;
						return;
				    }else{
				    	$.ajaxSettings.async = true;//执行异步，即弹出发送中提示时同时发送邮件
				    	toastr.info("邮件发送中...","提示", {"progressBar":true,"timeOut":4000});
				    	$.post("/user/sendEmail",{"username":username,"email":email},
				    			function(result){
				    		//2如果匹配：发送邮件，并提示成功
				    		if(result.success){
				    			toastr.success(result.errMsg,"提示");
				    		}else{
				    			toastr.error(result.errMsg, "提示");
				    		}
				    	});
				    }
				})
			}
		}
	})
})   
//注册
$("#registerBtn").click(function(){
	var bv = $('#registerForm').data('bootstrapValidator');
    bv.validate();
    if(bv.isValid()){
	   	var data = new FormData($("#registerForm")[0]); 
		data.append("headPicture",$('#headPicture')[0].files[0])
	    $.ajax({ 
	     type:'post',  
	     url:"/user/register", 
	     cache: false,    //上传文件不需缓存
	     processData: false, //需设置为false。因为data值是FormData对象，不需要对数据做处理
	     contentType: false, //需设置为false。因为是FormData对象，且已经声明了属性enctype="multipart/form-data"
	     data:data,  
	     //dataType:'json',后台用requestBody 
	     success:function(data){
	    	 bootbox.alert({
	    		    size: "small",
	    		    title: "提示",
	    		    message: "注册成功!",
	    		    callback: function(){
	    		    	$("#registerForm")[0].reset();
	    		    	$('#register').modal('hide');
	    		    }
	    		})
	     },
	     error:function(){ 
	    	bootbox.alert("注册失败!请重试", function () {})
	     }
	    })
    }
})

//注册校验
$('#registerForm').bootstrapValidator({
    message: '输入值不合法',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        username: {
            message: '用户名不合法',
            validators: {
                notEmpty: { message: '用户名不能为空'},
                stringLength: {min:2,max: 10,message: '请输入2到10个字符'},
                regexp: {regexp: /^[a-zA-Z0-9_\. \u4e00-\u9fa5 ]+$/,message: '用户名只能由字母、数字、点、下划线和汉字组成 '},
                threshold: 2,//有2字符以上才发送ajax请求
                remote: {//ajax验证。server result:{"valid",true or false} 
                    url: "/user/nameValidate?username="+$("#registerForm #username").val()+"&type=r",
                    message: '用户名已存在,请重新输入',
                    delay: 1000,//ajax刷新的时间是1秒一次
                    type: 'get',
                }
            }
        },realname: {
	        validators: {
	            notEmpty: { message: '昵称不能为空'},
	            stringLength: {min:2,max: 10,message: '请输入2到8个字符'},
	        }
	    }, email: {
            validators: {
                notEmpty: {message: 'email不能为空'},
                emailAddress: {message: '请输入正确的邮件地址如：123@qq.com'}
            }
        }, phone: {
            validators: {
                notEmpty: {message: '手机号不能为空'},
                regexp: {regexp: "^([0-9]{11})?$",message: '手机号码格式错误'}
            }
        }, password: {
            validators: {
                notEmpty: {message: '密码不能为空'}, 
                stringLength: {min:3,max:30,message: '请输入3到30个字符'},
                identical: {field: 'password1',message: '两次输入的密码不一致'}
            }
        }, password1: {
            validators: {
                notEmpty: {message: '密码不能为空'}, 
                stringLength: {min:3,max:30,message:'请输入3到30个字符'},
                identical: {field:'password',message:'两次输入的密码不一致'}
            }
        }, headPicture: {
            validators: {
                notEmpty: {message: '请上传头像'},
                file: {
                    extension: 'png,jpg,jpeg',
                    type: 'image/png,image/jpg,image/jpeg',
                    message: '请重新选择图片'
                }
            }
        }
    }
});

//登录用户名校验(值改变时校验)
$("#passForm #username").change(function(){ 
	$.get("/user/nameValidate?username="+$("#passForm #username").val()+"&type=l",function(result){
		var obj = JSON.parse(result);
		if(!obj.valid && $("#passForm #username").val()!=""){
			showPopover($("#passForm #username"),"用户名不存在!");
			$("#passForm #username").val("")
			return;
		}
	});
})

//重置密码校验
$('#resetForm').bootstrapValidator({
    message: '输入值不合法',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        password: {
            validators: {
                notEmpty: {message: '密码不能为空'}, 
                stringLength: {min:3,max:30,message: '请输入6到15个字符'},
                identical: {field: 'password2',message: '两次输入的密码不一致'}
            }
        }, password2: {
            validators: {
                notEmpty: {message: '密码不能为空'}, 
                stringLength: {min:3,max:30,message:'请输入6到15个字符'},
                identical: {field:'password',message:'两次输入的密码不一致'}
            }
        }
    }
});
//重置密码
$("#resetBtn").click(function(){
	var bv = $('#resetForm').data('bootstrapValidator');
    bv.validate();
    if(bv.isValid()){
		var username=$("#username").val();
		var password=$("#password").val();
		$.get("/user/resetPassword?username="+username+"&password="+password,function(result){
			if(result.success){
				$("#loginLink").css("display","")
				$("#resetBtn").prop('disabled', true);
			}
		})
    }
});
	